#include "tm1650.h"
#include "drv_pin.h"
#include "drv_soft_iic.h"
#include "main.h"
#include <stdio.h>
#include <stdbool.h>
#include "delay.h"

//命令代码
#define TM1650_SYS_CMD				0x48
#define TM1650_KEY_RD_CMD			0x4f

//亮度等级
#define TM1650_BRIGHT_LEVEL_1		0x11
#define TM1650_BRIGHT_LEVEL_2		0x21
#define TM1650_BRIGHT_LEVEL_3		0x31
#define TM1650_BRIGHT_LEVEL_4		0x41
#define TM1650_BRIGHT_LEVEL_5		0x51
#define TM1650_BRIGHT_LEVEL_6		0x61
#define TM1650_BRIGHT_LEVEL_7		0x71
#define TM1650_BRIGHT_LEVEL_8		0x01

//段显示
#define TM1650_SEGMENT_MODE_7		0x04
#define TM1650_SEGMENT_MODE_8		0x00

//工作模式
#define TM1650_WORK_MODE_NORMAL		0x00	//正常工作模式
#define TM1650_WORK_MODE_STANDY		0x02	//待机工作模式

//显存地址
#define TM1650_DIG1_ADDR			0x68
#define TM1650_DIG2_ADDR			0x6a
#define TM1650_DIG3_ADDR			0x6c
#define TM1650_DIG4_ADDR			0x6e

static Drv_I2c_Bus tm1650_iic_bus;
static int8_t soc_board_iic_index = 0;

static void tm1650_write(uint8_t add,uint8_t dat){//数码管显示
	//printf("tm1650_write:0x%02x\n",dat);
	//写显存必须从高地址开始写
	tm1650_iic_bus.start(soc_board_iic_index);
	tm1650_iic_bus.send_byte(soc_board_iic_index,add); //第一个显存地址
	tm1650_iic_bus.ask(soc_board_iic_index);
	tm1650_iic_bus.send_byte(soc_board_iic_index,dat); //第一个显存地址
	tm1650_iic_bus.ask(soc_board_iic_index);
	tm1650_iic_bus.stop(soc_board_iic_index);
}

void tm1650_sleep_enter(void){
//	hc32_pin_mode(LED_BOARD_SCL_PIN, PIN_MODE_INPUT_PULLDOWN);
//	hc32_pin_mode(LED_BOARD_SDA_PIN, PIN_MODE_INPUT_PULLDOWN);
}

void tm1650_sleep_exit(void){
//	hc32_pin_mode(LED_BOARD_SCL_PIN,PIN_MODE_OUTPUT_PULLUP);
//	hc32_pin_mode(LED_BOARD_SDA_PIN,PIN_MODE_OUTPUT_PULLUP);
	tm1650_write(TM1650_SYS_CMD,TM1650_SEGMENT_MODE_8 | TM1650_WORK_MODE_NORMAL | TM1650_BRIGHT_LEVEL_5);//初始化为8级灰度，开显示
}

void tm1650_set_value(uint8_t seg){//设置显示的段数(1-10)
	uint16_t sendCode = 0;
	uint8_t i = 0;
	for(i=0;i<seg;i++){
		sendCode |= (1<<i);
	}
	tm1650_write(TM1650_SYS_CMD,TM1650_SEGMENT_MODE_8 | TM1650_WORK_MODE_NORMAL | TM1650_BRIGHT_LEVEL_5);//初始化为8级灰度，开显示
	tm1650_write(TM1650_DIG3_ADDR,sendCode&0xff);		//前8段
	tm1650_write(TM1650_DIG4_ADDR,(sendCode>>8)&0x03);	//后2段
}

static void tm1650_set_bright_level(uint8_t level){
	if(level > 8){
		level = 8;
	}
	level %= 8;
	tm1650_write(TM1650_SYS_CMD,TM1650_SEGMENT_MODE_8 | TM1650_WORK_MODE_NORMAL | level);
}

void tm1650_init(void){
	if(soc_board_iic_index == 0){
		soc_board_iic_index = drv_i2c_register(LED_BOARD_SCL_PIN,LED_BOARD_SDA_PIN,&tm1650_iic_bus);
		if(soc_board_iic_index < 0){
			printf("soc board iic register faile!\n");
		}
	}
}